package coupon

import (
	sqlc "bp/db/sqlc"
	"bp/internal/render"
	"bp/internal/util"
	couponGrpc "bp/rpc/gen/mwebapi/mcoupon"
	"context"
)

// GettingCoupon 领取优惠券
func (s *CouponMWebApiImp) GettingCoupon(ctx context.Context, req *couponGrpc.GettingCouponReq) (res *couponGrpc.GettingCouponRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("coupon_imp/cmd.GettingCoupon=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &couponGrpc.GettingCouponRes{}

	var memberCouponPtr *sqlc.MemberCoupon
	var conv MemberCouponPtrEntityToPbFunc
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		CreateMemberCouponParam, distributionID, err := s.VldGettingCouponReq(ctx, q, req)
		if err != nil {
			return
		}
		memberCouponPtr, err = s.entityHub.MemberCouponService.CreateMemberCoupon(ctx, q, CreateMemberCouponParam)
		if err != nil {
			return
		}
		err = s.entityHub.MemberCouponService.RefreshMemberCouponGotStat(ctx, q, memberCouponPtr)
		if err != nil {
			return
		}

		go s.AsyncNotifyMemberGotCoupon(ctx, memberCouponPtr, distributionID)

		couponPtr, err := s.entityHub.CouponService.GetCouponPtr(ctx, q, memberCouponPtr.CouponID)
		if err != nil {
			return
		}
		conv = s.ConvMemberCouponPtrEntityToPbWithoutItemInfo(couponPtr)
		slog.Infof("领取优惠券 ok")
		return
	})
	if err != nil {
		return
	}
	res.MemberCoupon = conv(memberCouponPtr)
	return
}
